<template>
  <div class="user-select-component">
    <el-select
      v-select-scroll="!collapseTags"
      v-loadmore="loadmore"
      ref="scrollSelect"
      v-model="selectData"
      :disabled="disabled"
      :multiple="multiple"
      :filter-method="filterData"
      :filterable="filterable"
      :collapse-tags="collapseTags"
      :placeholder="placeholder"
      :clearable="clearable"
      :multiple-limit="multipleLimit"
      :value-key="valueType==='object'?keyName:''"
      :popper-class="'global-select-down '+extendClass"
      :loading="queryLoading"
      no-data-text="暂无数据"
      class="filterableSelect remoteRequestClient"
      size="small"
      @focus="$emit('focus')"
      @blur="searchVal = ''"
      @clear="clear"
      @change="selectChange"
      @visible-change="visibleChange"
    >
      <Options
        v-model="defaultList"
        :key-name="keyName"
        :label-name="labelName"
        :value-type="valueType"
        :extern-key="externKey"
        :open-tool-tip="openToolTip"
        :foot="foot" />
      <!-- 用于保存选中的数据，但是不显示在列表 -->
      <template v-if="selectDataList && selectDataList.length">
        <Options
          v-model="selectDataList"
          :key-name="keyName"
          :label-name="labelName"
          :value-type="valueType"
          :extern-key="externKey"
          :foot="foot"
          style="display:none;" />
      </template>
      <!-- 用于保存选中的数据，但是不显示在列表，少数需求会用到这个 -->
      <template v-if="hideSelectList">
        <Options
          v-model="hideSelectList"
          :key-name="keyName"
          :label-name="labelName"
          :value-type="valueType"
          :extern-key="externKey"
          :foot="foot"
          style="display:none;" />
      </template>
      <Options
        v-model="listData.items"
        :key-name="keyName"
        :label-name="labelName"
        :value-type="valueType"
        :extern-key="externKey"
        :open-tool-tip="openToolTip"
        :foot="foot" />
      <div v-if="areaName === 'resourceName' && !hasPlatform" class="no-data-tip">请先选择下单平台</div>
      <div v-else-if="dataLoading" class="no-data-tip">加载中...</div>
    </el-select>
  </div>
</template>

<script>
import Options from '@/components/Common/selectWithUserLoad/options';
import { _debounce } from '@/utils/tools';
export default {
  components: { Options },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String | Number,
      default: ''
    },
    defaultList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 当选中的项不在第一页时，可以使用这个属性：使输入框能够匹配到数据，该数据不会显示在下拉选项中
    hideSelectList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    extendParams: { // 传给接口额外的参数
      type: Object,
      default: null
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    labelName: { // label的字段
      type: String,
      default: 'userName'
    },
    keyName: { // key的字段
      type: String,
      default: 'id'
    },
    foot: {
      type: String,
      default: ''
    },
    externKey: {
      type: String,
      default: ''
    },
    multiple: { // 多选
      type: Boolean,
      default: false
    },
    multipleLimit: { // 多选限制
      type: Number,
      default: 0
    },
    filterable: { // 是否开启搜索
      type: Boolean,
      default: true
    },
    collapseTags: { // 折叠tag
      type: Boolean,
      default: true
    },
    clearable: { // 是否可以清除
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    valueType: { // 如果值为object,则值使用对象传输
      type: String,
      default: ''
    },
    extendClass: {
      type: String,
      default: ''
    },
    visibleChangeData: { // 下拉框出现时是否重新请求数据（前提：列表数据为空）
      type: Boolean,
      default: false
    },
    openToolTip: { // 是否展示列表的tooltip
      type: Boolean,
      default: false
    },
    showListData: {// 展示的数据
      type: Array,
      default: () => []
    },
    dataLoading: {
      type: Boolean,
      default: false
    },
    areaName: {// 单元格键名
      type: String,
      default: 'operatorId'
    },
    hasPlatform: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      userLoading: false,
      listData: { items: [] },
      selectDataList: [],
      selectDataItem: {},
      init: true,
      searchVal: '',
      queryLoading: false, // 接口数据loading
      rangeNumber: 10,
      options: []
    };
  },
  computed: {
    selectData: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('change', val);
      }
    }
  },
  watch: {
    showListData: {
      handler(newVal) {
        if (newVal && !this.listData.items.length) {
          this.listData.items = newVal;
        }
        this.options = newVal;
        this.filterData();
      },
      immediate: false
    },
    defaultList: {
      handler(newVal) {
        this.listData.items = this.handelDefaultUserList(this.listData.items);
        this.selectDataList = [...newVal];
      },
      immediate: true
    }
  },
  methods: {
    keyItem(item, foot) {
      if (item[foot]) {
        return `[${item[foot]}]`;
      }
      return '';
    },
    clear(e) {
      this.filterData();
      this.$emit('clear', e);
    },
    selectChange(value) {
      this.searchVal = '';
      const listData = this.listData.items;
      if (this.valueType === 'object') {
        this.selectDataList = value;
        this.$emit('changeMethod', this.selectDataList);
        return;
      }
      if (typeof value !== 'object') {
        this.selectDataItem = listData.find(i => {
          return i[this.keyName] === value;
        });
        let selectDataItem = {};
        if (value && this.defaultList.length && this.defaultList[0].id === value) {
          selectDataItem = this.defaultList[0];
        } else {
          selectDataItem = this.selectDataItem;
        }
        this.$emit('changeMethod', selectDataItem);
        return false;
      }
      if (value && value.length > 0) {
        listData.forEach(i => {
          if (value.includes(i.id)) {
            this.selectDataList.push(i);
          }
        });
        this.selectDataList = this.selectDataList.filter(i => {
          return value.includes(i.id);
        });
        this.selectDataList = this.uniqe(this.selectDataList);
      } else {
        this.selectDataList = [];
      }
      if (this.listData && this.listData.items.length === 0) this.filterData();
      this.$emit('changeMethod', this.selectDataList);
      const cacheList = this.selectDataList.map(item => {
        return {
          id: item.id,
          [this.labelName]: item[this.labelName]
        };
      });
      this.$emit('selectDataSave', JSON.stringify(cacheList)); // 缓存核算上一次填写的审批人员
    },
    // 去重
    uniqe(arr) {
      const result = [];
      const obj = {};
      for (let i = 0; i < arr.length; i++) {
        if (!obj[arr[i].id]) {
          result.push(arr[i]);
          obj[arr[i].id] = true;
        }
      }
      return result;
    },
    loadmore(val) {
      this.rangeNumber += 5; // 每次滚动到底部可以新增条数
      this.listData.items = this.options.slice(0, this.rangeNumber);
    },
    filterData: _debounce(function(filterVal) { // 通过名称检索
      if (filterVal) {
        const filterArr = this.showListData.filter((item) => {
          return item[`${this.areaName}`].toLowerCase().includes(filterVal.toLowerCase());
        });
        this.options = filterArr;
      } else {
        this.options = this.showListData;
      }
      this.$set(this.listData, 'items', this.options.slice(0, 10));
    }, 300),
    // 从用户列表中去除 defaultList 已经有的数据
    handelDefaultUserList(listData) {
      let res = [];
      if (listData && listData.length) {
        const ids = this.defaultList.map(i => i.id);
        res = listData.filter(i => {
          return !ids.includes(i.id);
        });
      }
      return res;
    },
    visibleChange(flag, row) {
      if (flag) {
        this.$nextTick(() => {
          this.filterData();
        });
      }
    },
    handleAddNew() {
      this.$emit('addNewClick');
    }
  }
};
</script>

<style lang="scss" scoped>
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
.no-data-tip {
  width: 100%;
  text-align: center;
  height: 34px;
  line-height: 34px;
  color: #999;
}
.user-select-component {
  &::v-deep {
    .filterableSelect {
      width: 100%;
    }
    .el-tag.el-tag--info {
      color: #406eff;
      background: #eff3fb;
    }
    .el-tag__close{
      flex-shrink: 0;
      // right:-1px !important;
    }
  }
}
.select-extend-btn {
  cursor: pointer;
  border-bottom: 1px solid #ddd;
  .select-extend-btn-text {
    color: #406eff;
  }
}
</style>
